<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\PaymentAgentCashSource as PaymentAgentCashSourceModel;
use app\payment\model\Download as DownloadModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 代理金额每天来源控制器
 */
class AgentCashSource extends Index
{

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
                if ($map_v1[0] == 'agent_id') {
                    $search_agent_id_key = $map_k1;
                    $search_agent_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);
        $search_agent_id_key = isset($search_agent_id_key) ? $search_agent_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $map[$search_agent_id_key] = ['agent_id', '=', $this->merchant_id];
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
                $map[$search_agent_id_key] = ['agent_id', 'in', $this->merchant_id];
                if (isset($search_agent_id) && in_array($search_agent_id, $sub_merchant)) {
                    $map[$search_agent_id_key] = ['agent_id', '=', $search_agent_id];
                }
            }
        }

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = PaymentAgentCashSourceModel::where($map)->order('create_time desc')->paginate($list_rows);
        $sum_count = PaymentAgentCashSourceModel::where($map)->count();
        $balance_cash = PaymentAgentCashSourceModel::where($map)->sum('balance_cash');
        $balance_cash /= 100;
        $agent_balance_cash = PaymentAgentCashSourceModel::where($map)->sum('agent_balance_cash');
        $agent_balance_cash /= 100;
        // 分页数据
        $page = $data_list->render();

        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');
        $date = date('Y-m-d');
        $search = [
            ['daterange:6', 'create_time', '时间查询', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'status', '支付状态', '', '', ['禁用', '启用']],
            ['select:3', 'trade_type', '交易类型', '', '', $all_trade_type],
            ['text:3', 'order_id', '本地订单号'],
            ['text:3', 'source_order_id', '来源订单号'],
            ['text:3', 'source_merchant_id', '间接来源商户号'],
            ['text:3', 'agent_id', '代理商户号'],
            ['text:3', 'merchant_id', '充值商户号'],
        ];

        $items = [
            ['order_id', '本地订单号'],
            ['source_order_id', '来源订单号'],
            ['agent_id', '代理商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['merchant_id', '充值商户', 'callback', function ($value) {
                return $value . '<br/>' . get_user_nickname($value);
            }, '', 'text-center'],
            ['agent_balance_cash', '代理商户结算金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['balance_cash', '充值商户结算金额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['agent_before_cash', '代理原余额', 'callback', function ($value) {
                return $value / 100;
            }],
            ['dates', '统计日期', 'callback', function ($value) {
                return date('Y-m-d', strtotime($value));
            }],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'status'],
            ['right_button', '操作', 'btn']
        ];

        if ($this->no_auth) {
            // 去掉显示搜索项
            unset($search[7]);
            // 去掉显示列
            unset($items[6]);
        }
        if ($this->is_agent) {
            // 显示搜索项
            $search[] = ['text:3', 'merchant_id', '充值商户号'];
        }

        $describe = [
            'title' => "总笔数：{$sum_count} 笔    充值商户结算金额：{$balance_cash} 元    代理商户结算金额：{$agent_balance_cash} 元",
            'icon' => 'fa fa-fw fa-jpy',
            'class' => 'btn btn-xs btn-info',
        ];
        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setPageTitle('代理账户返利明细') // 设置页面标题
            ->setTableName('payment_agent_cash_source') // 设置数据表名
            ->setPrimaryKey('order_id') // 设置主键名为id
            ->setSearchArea($search) // 设置搜索区域
            ->addColumns($items)
            ->addTopButton('describe', $describe) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            //->addTopButtons('add') // 批量添加顶部按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');

        $search_merchant_id = isset($map['merchant_id']) ? $map['merchant_id'][1] : false;
        $search_agent_id = isset($map['agent_id']) ? $map['agent_id'][1] : false;

        if ($map) {
            foreach ($map as $map_k1 => $map_v1) {

                if ($map_v1[0] == 'merchant_id') {
                    $search_merchant_id_key = $map_k1;
                    $search_merchant_id = $map[$map_k1][2];
                }
                if ($map_v1[0] == 'agent_id') {
                    $search_agent_id_key = $map_k1;
                    $search_agent_id = $map[$map_k1][2];
                }
            }
        }

        $search_merchant_id_key = isset($search_merchant_id_key) ? $search_merchant_id_key : count($map);
        $search_agent_id_key = isset($search_agent_id_key) ? $search_agent_id_key : count($map);

        if ($this->no_auth) {
            $map[$search_merchant_id_key] = ['merchant_id', '=', $this->merchant_id];
        }

        if ($this->is_agent) {
            $map[$search_agent_id_key] = ['agent_id', '=', $this->merchant_id];
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if ($sub_merchant) {
                $sub_merchant[] = $this->merchant_id;
                $map[$search_merchant_id_key] = ['merchant_id', 'in', $sub_merchant];
                if (isset($search_merchant_id) && in_array($search_merchant_id, $sub_merchant)) {
                    $map[$search_merchant_id_key] = ['merchant_id', '=', $search_merchant_id];
                }
                $map[$search_agent_id_key] = ['agent_id', 'in', $this->merchant_id];
                if (isset($search_agent_id) && in_array($search_agent_id, $sub_merchant)) {
                    $map[$search_agent_id_key] = ['agent_id', '=', $search_agent_id];
                }
            }
        }

        $count = PaymentAgentCashSourceModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }

        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "每日代理返利统计导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败！");
        }

        $field = [
            'order_id',
            'source_order_id',
            'merchant_id',
            'source_merchant_id',
            'agent_id',
            'payment_type_cash_count',
            'payment_type_rate',
            'source_agent_payment_type_rate',
            'agent_payment_type_rate',
            'payment_type_balance_cash',
            'source_agent_payment_type_balance_cash',
            'agent_payment_type_balance_cash',
            'app_id',
            'balance_cash',
            'agent_balance_cash',
            'agent_before_cash',
            'trade_type',
            'dates',
            'settlement_type',
            'settlement_day',
            'relation',
            'status',
            'create_time',
            'update_time',
        ];
        if ($this->no_auth) {
            unset($field[7]);
            unset($field[8]);
        }
        $cellName = [
            '本地订单号',
            '充值来源订单号',
            '充值商户号',
            '间接来源商户号',
            '代理商户号',
            '充值商户支付类型金额和数量json格式',
            '充值商户支付类型费率',
            '间接代理支付类型费率',
            '代理支付类型费率',
            '充值商户支付类型结算金额json格式',
            '间接代理支付类型结算金额json格式',
            '代理支付类型结算金额json格式',
            '充值的订单包括哪些应用ID',
            '充值商户结算金额',
            '代理结算金额',
            '代理统计之前的余额',
            '交易类型',
            '统计日期',
            '结算类型',
            '结算天数',
            '关系层级',
            '状态',
            '创建时间',
            '更新时间',
        ];
        if ($this->no_auth) {
            unset($cellName[7]);
            unset($cellName[8]);
        }

        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_agent_cash_source')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp, $all_trade_type) {
                foreach ($all as $single) {

                    $single['balance_cash'] /= 100;
                    $single['agent_balance_cash'] /= 100;
                    $single['agent_before_cash'] /= 100;

                    $single['trade_type'] = $all_trade_type[$single['trade_type']];

                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);
                    $single['update_time'] = date('Y-m-d H:i:s', $single['update_time']);
                    $single['status'] = $single['status'] ? '开启' : '禁用';
                    $single['settlement_type'] = $single['settlement_type'] ? 'D' : 'T';

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['merchant_id', 'source_merchant_id', 'agent_id', 'balance_cash', 'agent_balance_cash', 'agent_before_cash'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'order_id', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 所有的交易类型
        $all_trade_type = pay_config('trade_type');

        // 获取数据
        $info = PaymentAgentCashSourceModel::where('order_id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        if ($this->is_agent) {
            $sub_merchant = get_sub_merchant($this->merchant_id);
            if (in_array($info['agent_id'], $sub_merchant)) {
                $see_auth = true;
            }
            if (in_array($info['merchant_id'], $sub_merchant)) {
                $see_auth = true;
            }
        }

        if ($this->no_auth) {
            if (!isset($see_auth) && $this->merchant_id != $info['merchant_id']) {
                $this->error('参数错误！');
            }
        }

        $info['balance_cash'] /= 100;
        $info['agent_balance_cash'] /= 100;
        $info['agent_before_cash'] /= 100;
        $info['trade_type'] = isset($all_trade_type[$info['trade_type']]) ? $all_trade_type[$info['trade_type']] : '';
        $info['payment_type_cash_count'] = format_nice($info['payment_type_cash_count']);
        $info['payment_type_rate'] = format_nice($info['payment_type_rate']);
        $info['payment_type_balance_cash'] = format_nice($info['payment_type_balance_cash']);
        $info['source_agent_payment_type_rate'] = format_nice($info['source_agent_payment_type_rate']);
        $info['source_agent_payment_type_balance_cash'] = format_nice($info['source_agent_payment_type_balance_cash']);
        $info['agent_payment_type_rate'] = format_nice($info['agent_payment_type_rate']);
        $info['agent_payment_type_balance_cash'] = format_nice($info['agent_payment_type_balance_cash']);
        $info['app_id'] = format_nice($info['app_id']);
        $info['merchant_config'] = format_nice($info['merchant_config']);

        $items = [
            ['static', 'order_id', '本地订单号'],
            ['static', 'source_order_id', '充值来源订单号'],
            ['static', 'merchant_id', '充值商户号', '商户名称：' . get_user_nickname($info['merchant_id']), '', '', ''],
            ['static', 'source_merchant_id', '间接来源商户号', '商户名称：' . get_user_nickname($info['source_merchant_id']), '', '', ''],
            ['static', 'agent_id', '代理商户号', '商户名称：' . get_user_nickname($info['agent_id']), '', '', ''],
            ['textarea', 'payment_type_cash_count', '充值商户支付类型金额和数量json格式', '', '', '', ''],
            ['textarea', 'payment_type_rate', '充值商户支付类型费率', '', '', '', ''],
            ['textarea', 'source_agent_payment_type_rate', '间接代理商户支付类型费率', '', '', '', ''],
            ['textarea', 'agent_payment_type_rate', '代理商户支付类型费率', '', '', '', ''],
            ['textarea', 'payment_type_balance_cash', '充值商户支付类型结算金额json格式', '', '', '', ''],
            ['textarea', 'source_agent_payment_type_balance_cash', '间接代理商户支付类型结算金额json格式', '', '', '', ''],
            ['textarea', 'agent_payment_type_balance_cash', '代理商户支付类型结算金额json格式', '', '', '', ''],
            ['textarea', 'app_id', '充值商户充值的订单包括哪些应用ID', '', '', '', ''],
            ['static', 'balance_cash', '充值商户结算金额（元）', ''],
            ['static', 'agent_balance_cash', '代理商户结算金额（元）', ''],
            ['static', 'agent_before_cash', '代理统计之前的余额（元）', ''],
            ['static', 'relation', '关系层级', ''],
            ['static', 'trade_type', '交易类型', ''],
            ['static', 'dates', '统计日期', ''],
            ['radio', 'settlement_type', '结算类型', 'T是交易日，D是自然日', ['T', 'D'], '', '', 'disabled', ''],
            ['static', 'settlement_day', '结算天数', ''],
            ['radio', 'status', '状态', '', ['禁用', '启用'], '', '', 'disabled', ''],
            ['datetime', 'create_time', '订单创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '订单更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['textarea', 'merchant_config', '商户配置', '', '', '', ''],
        ];
        if ($this->no_auth) {
            unset($items[7]);
            unset($items[8]);
        }
        if ($this->role > $this->have_auth) {
            array_pop($items);
        }
        if (!$this->key_see_safe) {
            array_pop($items);
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }
}
